package com.xiyu.service.repository.bed.room;

import com.xiyu.service.model.bed.bed.BedInfoFetcher;
import com.xiyu.service.model.bed.building.BuildingInfoFetcher;
import com.xiyu.service.model.bed.room.RoomInfo;
import com.xiyu.service.model.bed.room.RoomInfoFetcher;
import com.xiyu.service.model.bed.room.RoomInfoTable;
import com.xiyu.service.model.bed.room.RoomTypeFetcher;
import com.xiyu.service.vo.bed.bedInfo.BedInfoRoomQueryInput;
import org.babyfish.jimmer.spring.repository.JRepository;
import org.babyfish.jimmer.Page;
import org.springframework.util.StringUtils;

import java.util.Optional;

public interface RoomInfoRepository extends JRepository<RoomInfo, Long> {
    RoomInfoTable roomInfoTable = RoomInfoTable.$;

    default Page<RoomInfo> pageQuery(BedInfoRoomQueryInput inputVO){
        return sql().createQuery(roomInfoTable)
                .whereIf(StringUtils.hasText(inputVO.getRoomName()), () ->  roomInfoTable.roomName().like(inputVO.getRoomName()))
                .whereIf(StringUtils.hasText(inputVO.getBedName()), () ->  roomInfoTable.asTableEx().beds().bedName().like(inputVO.getRoomName()))
                .whereIf(inputVO.getBedTypeId() != null, roomInfoTable.asTableEx().beds().bedTypeId().eq(inputVO.getBedTypeId()))
                .whereIf(inputVO.getBuildingId() != null, roomInfoTable.buildingId().eq(inputVO.getBuildingId()))
                .whereIf(inputVO.getRoomTypeId() != null, roomInfoTable.roomTypeId().eq(inputVO.getRoomTypeId()))
                .orderBy(roomInfoTable.id().desc())
                .select(roomInfoTable.fetch(RoomInfoFetcher.$.allTableFields()
                        .roomType(RoomTypeFetcher.$.allTableFields())
                        .building(BuildingInfoFetcher.$.allTableFields())))
                .fetchPage(inputVO.getPageNo() - 1, inputVO.getPageSize());
    }

    default Optional<RoomInfo> findDetailById(Long id){
        return sql().createQuery(roomInfoTable)
                .where(roomInfoTable.id().eq(id))
                .select(roomInfoTable.fetch(RoomInfoFetcher.$.allTableFields().beds(BedInfoFetcher.$.allTableFields())))
                .fetchOptional();
    }

    Optional<RoomInfo> findFirstByRoomName(String roomName);

    Optional<RoomInfo> findFirstByRoomNameAndIdNot(String roomName, Long Id);

}